package cn.nextProject.service.impl;

import cn.nextProject.entity.Permission;
import cn.nextProject.mapper.PermissionMapper;
import cn.nextProject.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @CacheEvict(value = {"permissionList","permissions","permissionListAll","permissionMap"}, allEntries = true, beforeInvocation = true)
    @Override
    public void saveBatch(List<Permission> permissions) {
        if (!CollectionUtils.isEmpty(permissions)){
            permissionMapper.saveBatch(permissions);
        }
    }

    @CacheEvict(value = {"permissionList","permissions","permissionListAll","permissionMap"}, allEntries = true, beforeInvocation = true)
    @Override
    public void saveBatchHasId(List<Permission> permissionList) {
        if (!CollectionUtils.isEmpty(permissionList)){
            permissionMapper.saveBatchHasId(permissionList);
        }
    }

    @CacheEvict(value = {"permissionList","permissions","permissionListAll","permissionMap"}, allEntries = true, beforeInvocation = true)
    @Override
    public void update(Permission permission) {

        if (ObjectUtils.isEmpty(permission)){
            return;
        }

        permissionMapper.update(permission);

    }

    @Cacheable(value = "permissionListAll")
    @Override
    public List<Permission> findAll() {
        return permissionMapper.findAll();
    }

    @Cacheable(value = "permissionMap")
    @Override
    public Map<String, Permission> findAllMap() {
        Map<String,Permission> permissionMap = new HashMap<>();
        List<Permission> all = findAll();
        if (!CollectionUtils.isEmpty(all)){
            all.forEach(permission -> {
                permissionMap.put(permission.getPath(),permission);
            });
        }
        return permissionMap;
    }

    @CacheEvict(value = {"permissionList","permissions","permissionListAll","permissionMap"}, allEntries = true, beforeInvocation = true)
    @Override
    public void deleteAll() {
        permissionMapper.deleteAll();
    }

    @Cacheable(value = "permissions", key = "#roleGroupId")
    @Override
    public List<Permission> findByNotIn(Long roleGroupId) {
        return permissionMapper.findByNotIn(roleGroupId);
    }
}
